package com.oc.mba.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.xpath.XPathConstants;

import javax.xml.namespace.QName;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.dom4j.DocumentException;
import org.xml.sax.InputSource;
/**
 * ACM系统配置管理工具,用来读取各种配置文件
 * @author unidw
 * 
 */
public class ConfigUtil {

	final static Logger log = LoggerFactory.getLogger(ConfigUtil.class);
	private static Properties cfg;

	/**
	 * 重置系统配置文件的方法
	 * 
	 */
	public static synchronized void reset() {
		if (cfg == null)
			return;
		cfg.clear();
		cfg = null;
	}

	
	/**
	 * 按配置文件名，读取配置文件的信息 
	 * @param configFile  配置文件名
	 * @return
	 */
	public static synchronized boolean load(String configFile) {
		if (cfg == null) {
			InputStream is = null;
			try {
                 //读取配置文件
				is = ConfigUtil.class.getResourceAsStream(configFile);
				if (is != null) {
					cfg = new Properties();
					cfg.load(is);
					return true;
				} else {
					log.error("The properties file of " + configFile + " was not loaded properly!");
					return false;
				}

			} catch (IOException e) {
				log.error(e.getMessage());
				return false;
			} catch (NullPointerException e) {
				log.error(e.getMessage(),e);
				return false;
			} finally {
				//关闭连接，释放内存
				if (is != null) {
					try {
						is.close();
					} catch (IOException e) {
						log.error(e.getMessage(),e);
					}
				}
			}
		} else {
			return true;
		}
	}

	
	/**
	 * 根据键值获得属性值
	 * @param key
	 * @return
	 */
	public static synchronized String getConfig(String key) {
		if (cfg == null) {
//			log.error("load must be called in advance!");
			return null;
		}
		return cfg.getProperty(key);
	}
	
	/**
	 * 根据键值获得属性值
	 * @param key
	 * @return
	 */
	public static synchronized List<String> getConfigAll(String pre) {
		if (cfg == null) {
//			log.error("load must be called in advance!");
			return null;
		}
		Set<Object> key= cfg.keySet();
		Iterator<Object> it=key.iterator();
		List<String> list=new ArrayList<String>();
		while(it.hasNext()){
			String SSCKey=(String) it.next();
			String[] SSCKeyArr=SSCKey.split("\\.");
			if(SSCKeyArr[0].equals(pre)){
				list.add(SSCKey);
			}
		}
		
		return list;
	}

	/**
	 * 获得当前的配置对象 
	 * @return
	 */
	public static synchronized Properties getConfigs() {

		if (cfg == null) {
//			log.error("load must be called in advance!");
			return null;
		}

		return cfg;
	}
	
	/**
	 * @brief 得到返回指定的expression的Object
	 * @param systemConfig
	 * @param expression
	 * @param qname
	 * @return
	 * @throws DocumentException
	 * @throws XPathExpressionException
	 * @throws FileNotFoundException
	 */
	@SuppressWarnings("unused")
	public static Object getXpathNsContext(String systemConfig, String expression, QName qname) throws DocumentException, XPathExpressionException, FileNotFoundException {
		XPathFactory factory = XPathFactory.newInstance();
		XPath xPath = factory.newXPath();
		XPathExpression xpathExpression = xPath.compile(expression);
		InputSource inputSource = new InputSource(ConfigUtil.class.getResourceAsStream(systemConfig));
		Object obj =xpathExpression.evaluate(inputSource, qname);
		return obj;
	}
	
	/**
	 * @brief 得到节点的内容
	 * @param systemConfig
	 * @param expression
	 * @return
	 * @throws DocumentException
	 * @throws XPathExpressionException
	 * @throws FileNotFoundException
	 */
	@SuppressWarnings("unused")
	public static String getNodeContent(String systemConfig, String expression) throws DocumentException, XPathExpressionException, FileNotFoundException {
		String content = null;
		XPathFactory factory = XPathFactory.newInstance();
		XPath xPath = factory.newXPath();
		XPathExpression xpathExpression = xPath.compile(expression);
		InputSource inputSource = new InputSource(ConfigUtil.class.getResourceAsStream(systemConfig));
		content =xpathExpression.evaluate(inputSource);
		return content;
	}
	
	public static void loadSignIDs() {
		//得到System的配置信息
		String interfaceExpression = "/reqs/req";
		try {
			NodeList signIDList = (NodeList) getXpathNsContext("/req.xml", interfaceExpression, XPathConstants.NODESET);
			for (int i =0;i< signIDList.getLength();i++) {
				Node signIDChild = signIDList.item(i);
				NodeList childList = signIDChild.getChildNodes();
				Map<String, String> signIDMap = new HashMap<String, String>();
				// 取得所有case节点
				for (int j = 0; j < childList.getLength(); j++) {
					Node node = childList.item(j);
					if (node instanceof Element) {
						signIDMap.put(node.getNodeName(), node.getTextContent());
					}
				}
				String signID = signIDMap.get("signID");
				String controllerName = signIDMap.get("controllerName");
				OcConfig.addSignID(signID, controllerName);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		loadSignIDs();
		System.out.println(OcConfig.getSignIDs().toString());
	}
}
